<template>
  <div class="flex-col-center-start text-practice">
    <div class="option-box flex-col-center-start">

      <div class="flex-row-center margin-col-10 clickable" @click="showTollgateList=!showTollgateList">
        <el-icon>
          <User/>
        </el-icon>
        关卡
      </div>
      <div class="flex-row-center clickable" @click="showScheme=!showScheme">
        <el-icon>
          <Fold/>
        </el-icon>
        方案
      </div>
    </div>
    <!--    方案抽屉-->
    <el-drawer v-model="showScheme" :show-close="true" :size="computedSizeByIsPc" destroy-on-close>
      <template #header>
        <div>我的方案</div>
      </template>
      <personal-scheme-box @select-tollgate="handleSelectSchemeTollgate"
                           @selectScheme="handelSelectScheme"></personal-scheme-box>
    </el-drawer>

    <el-drawer v-model="showTollgateList" :show-close="true" :size="computedSizeByIsPc">
      <template #header>
        <div>关卡选择</div>
      </template>
      <TollgateBox @select-tollgate="handleSwitchTollgate" :scheme-id="activeScheme.id"></TollgateBox>
    </el-drawer>

    <div class="flex-col-center width-100-percent" style="min-height: 50vh;"
         v-loading="showTollgateLoading"
         element-loading-text="加载关卡中"
    >
      <EnglishTollgate @end="handleTollgateEnd" :tollgate="activeTollgate"
                       v-if="activeTollgate.id !== '0' && activeTollgate.tollgateType === TollgateType.ENGLISH"></EnglishTollgate>
      <ChineseTollgate @end="handleTollgateEnd" :tollgate="activeTollgate"
                       v-if="activeTollgate.id !== '0'  && activeTollgate.tollgateType === TollgateType.CHINESE"></ChineseTollgate>

      <el-empty description="暂无选择方案" v-if="activeScheme.id === '0'">
        <el-button :color="sysConfig.DARK_COLOR" @click="showScheme=true">
          点击选择方案
        </el-button>
        <el-button :color="sysConfig.DARK_COLOR" @click="router.push('/home/scheme/square')">
          更多方案
        </el-button>
      </el-empty>
      <el-empty description="暂无关卡" v-if="activeScheme.id !== '0' && activeTollgate.id === '0'">

      </el-empty>
      <div v-show="activeScheme.id !== '0'" class="flex-row-between" style="width: 30%">
        <el-button text :icon="ArrowLeft" @click="lastTollgate">上一关</el-button>
        <el-popover

            :width="300"
            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
        >
          <template #reference>
            <el-avatar :src="activeScheme.imagesrc"></el-avatar>
          </template>
          <template #default>
            <el-descriptions :column="1" title="方案信息">
              <el-descriptions-item label="方案名">{{ activeScheme.schemeName }}</el-descriptions-item>
              <el-descriptions-item label="关卡名">{{ activeTollgate.tollgateName }}</el-descriptions-item>
              <el-descriptions-item label="上一关">{{ computedLastTollgateName }}</el-descriptions-item>
              <el-descriptions-item label="下一关">{{ computedNextTollgateName }}</el-descriptions-item>
            </el-descriptions>
          </template>
        </el-popover>
        <el-button text  @click="nextTollgate">
          <span :style="{color: sysConfig.DANGER_COLOR}">下一关</span>
          <el-icon :color="sysConfig.DANGER_COLOR">
            <ArrowRight></ArrowRight>
          </el-icon>
        </el-button>
      </div>


    </div>
    <ResultDialog
        v-model="showResult" title="最终结果"
        :list="resultList">
      <template #footer>
        <div class="flex-row-between">
          <el-button @click="lastTollgate">上一关</el-button>
          <el-button @click="nextTollgate">下一关</el-button>
        </div>
      </template>
    </ResultDialog>

  </div>
</template>

<script setup lang="ts">


import {computed, ref} from "vue";

import PersonalSchemeBox from "@/components/scheme/PersonalSchemeBox.vue";
import EnglishTollgate from "@/components/tollgate/EnglishTollgate.vue";
import {ArrowLeft, ArrowRight, Fold, User} from "@element-plus/icons";
import ChineseTollgate from "@/components/tollgate/ChineseTollgate.vue";
import {SchemeManageCardType} from "@/components/scheme/SchemeManageCard.vue";
import {Chapter, Scheme, SchemeStatus, SchemeType, Tollgate, TollgateType} from "@/ts/scheme";
import {ElMessage, ElMessageBox} from "element-plus";

import TollgateBox from "@/components/tollgate/TollgateBox.vue";
import {isPC} from "@/utils/CommonUtil";
import router from "@/router";
import {RecordItem} from "@/ts/record";
import ResultDialog from "@/components/result/ResultDialog.vue";
import {getAllTollgateList, getTollgateById} from "@/api/tollgate/TollgateApi";
import sysConfig from "@/config/index"
import {getChaptersWithTollgates} from "@/api/chapter/ChapterApi";
// 显示结果
let showResult = ref(false)
// 显示方案列表
let showScheme = ref(false)
// 关卡加载开关
let showTollgateLoading = ref(false)
// 当前选中的方案id
let activeScheme = ref<Scheme>({
  chapterList: [],
  collection: false,
  collectionNum: 0,
  createTime: "",
  description: "",
  id: "0",
  imagesrc: "",
  mark: 0,
  maxAge: 0,
  minAge: 0,
  price: 0,
  schemeName: "",
  schemeStatus: SchemeStatus.PRIVATE,
  schemeType: SchemeType.EXERCISE

})
// 关卡索引
let activeTollgateIndex = ref(0)
let tollgateList = ref<Tollgate[]>([])
// 当前关卡
let activeTollgate = ref<Tollgate>({
  commonSpeed: 0,
  content: "",
  icon: "",
  id: "0",
  maxPassError: 0,
  maxPassTime: 0,
  maxSpeed: 0,
  minSpeed: 0,
  passScore: 0,
  progress: 0,
  tollgateName: "",
  tollgateType: TollgateType.CHINESE

})

// 关卡选择抽屉
let showTollgateList = ref(false)
let resultList = ref<RecordItem[]>([])


// 根据tollgateId请求tollgate信息
function getTollgate(id: string): void {
  showTollgateLoading.value = true
  getTollgateById(id).then(resp => {
    if (resp.code === 200) {
      activeTollgate.value = resp.data
    }
    showTollgateLoading.value = false
  })


}

function initScheme(){

  activeScheme.value={
    chapterList: [],
    collection: false,
    collectionNum: 0,
    createTime: "",
    description: "",
    id: "0",
    imagesrc: "",
    mark: 0,
    maxAge: 0,
    minAge: 0,
    price: 0,
    schemeName: "",
    schemeStatus: SchemeStatus.PRIVATE,
    schemeType: SchemeType.EXERCISE
  }

}
function initTollgate(){
  activeTollgate.value ={
    commonSpeed: 0,
    content: "",
    icon: "",
    id: "0",
    maxPassError: 0,
    maxPassTime: 0,
    maxSpeed: 0,
    minSpeed: 0,
    passScore: 0,
    progress: 0,
    tollgateName: "",
    tollgateType: TollgateType.CHINESE

  }
  showResult.value=false
}




// 用户选择方案后
function handelSelectScheme(scheme: SchemeManageCardType) {
  initScheme()
  initTollgate()
  activeScheme.value=scheme
  getChaptersWithTollgates(scheme.id).then(resp=>{
    if(resp.code === 200){
      let lst:Chapter[] = resp.data
      for (let chapter of lst) {
        tollgateList.value.push(...chapter.tollgateList)
      }
      if(tollgateList.value.length === 0){
        return
      }
      activeTollgateIndex.value=0
      activeTollgate.value=tollgateList.value[activeTollgateIndex.value]
    }
  })
  // 隐藏方案抽屉
  showScheme.value = false

}


// 直接选择某个方案下的某个关卡
function handleSelectSchemeTollgate(scheme: SchemeManageCardType, tollgate: Tollgate, chapter: Chapter) {

 initScheme()
  initTollgate()
  activeScheme.value=scheme
  getChaptersWithTollgates(scheme.id).then(resp=>{
    if(resp.code === 200){
      let lst:Chapter[] = resp.data
      for (let chapter of lst) {
        tollgateList.value.push(...chapter.tollgateList)
      }
      if(tollgateList.value.length === 0){
        return
      }
      activeTollgateIndex.value=tollgateList.value.findIndex(item=>item.id === tollgate.id)
      activeTollgate.value=tollgateList.value[activeTollgateIndex.value]
    }
  })
  // 隐藏方案抽屉
  showScheme.value = false
}

// 当前已有方案，切换关卡
function handleSwitchTollgate(tollgate: Tollgate, chapter: Chapter) {
  // 提示
  ElMessageBox.confirm("确定切换该关卡吗?\n此操作可能会丢失当前进度!", {
    title: "提示",
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    initTollgate()
    activeTollgateIndex.value=tollgateList.value.findIndex(item=>item.id === tollgate.id)
    activeTollgate.value=tollgateList.value[activeTollgateIndex.value]


    ElMessage({
      type: "success",
      message: "切换成功"
    })
//   隐藏关卡盒
    showTollgateList.value = false
  }).catch(() => {
    // 还原值

  })


}

function lastTollgate() {
  if (activeTollgateIndex.value === 0) {
    ElMessage({
      type:"warning",
      message:"已经是第一关啦!"
    })
    return
  }
  initTollgate()
  activeTollgateIndex.value -= 1
  activeTollgate.value=tollgateList.value[activeTollgateIndex.value]

}

function nextTollgate() {
  if (activeTollgateIndex.value === tollgateList.value.length - 1) {
    ElMessage({
      type:"warning",
      message:"已经是最后一关啦!"
    })
    return
  }
  initTollgate()
  activeTollgateIndex.value += 1
  activeTollgate.value=tollgateList.value[activeTollgateIndex.value]
}

function handleTollgateEnd(results: RecordItem[]) {
  // 提示
  ElMessage({
    type: "success",
    message: "完成!"
  })
  // 赋值
  resultList.value = results
  // 显示
  showResult.value = true
}

let computedSizeByIsPc = computed(() => {
  return isPC() ? '80%' : '100%'
})

let  computedLastTollgateName=computed(()=>{

  if(activeTollgateIndex.value === 0){
    return '无'
  }
  if(tollgateList.value.length === 0){
    return '无'
  }
  return tollgateList.value[activeTollgateIndex.value-1].tollgateName
})
let  computedNextTollgateName=computed(()=>{
  if(activeTollgateIndex.value === tollgateList.value.length-1){
    return '无'
  }
  if(tollgateList.value.length === 0){
    return '无'
  }
  return tollgateList.value[activeTollgateIndex.value+1].tollgateName
})
</script>

<style scoped lang="less">
.text-practice {
  width: 100%;

  .option-box {
    position: fixed;
    right: 50px;
    bottom: 50px;
  }

  .scheme-btn {

  }
}
</style>